import { useRequest } from 'ahooks'
import { getQuestionListFun } from '../api/list'
import { useSearchParams } from 'react-router-dom'
import { LIST_SEARCH_PARMA_KEY, PAGE_NUMBER_KEY, PAGE_SIZE_KEY } from '../constant'

/**
 * 问卷搜索参数
 * @param title 问卷标题
 * @param isDelete 是否删除
 * @param star 是否标星
 */
type QuestionSearchProp = {
  isDelete: number
  isStar: boolean
}

// 将查询问卷列表的功能单独抽离成一个单独的hooks，方便复用
export function useLoadQuestionListData(
  params: Partial<QuestionSearchProp> = {
    isDelete: 0
  }
) {
  const [searchParam] = useSearchParams()

  const { data, loading, refresh } = useRequest(
    async () => {
      const data = await getQuestionListFun({
        title: searchParam.get(LIST_SEARCH_PARMA_KEY) || '',
        ...params,
        pageNum: parseInt(searchParam.get(PAGE_NUMBER_KEY) || '1'),
        pageSize: parseInt(searchParam.get(PAGE_SIZE_KEY) || '10')
      })
      return data
    },
    {
      refreshDeps: [searchParam] // 监听搜索参数的变化，重新请求数据
    }
  )
  return {
    data,
    loading,
    refresh // 手动刷新
  }
}
